<template>
  <view class="bg-white flex flex-col h-auto">
    <nav-bar title="新增会员" color="white" bg-color="#111827" show-back></nav-bar>
    <view class="content p-20rpx flex-auto">
      <u-row gutter="10rpx" custom-style="flex:auto;align-items: baseline;">
        <u-col span="9" custom-style="">
          <u-form ref="refForm" :model="formData" :rules="formRules" label-width="5rem" label-position="top">
            <view class="flex justify-between">
              <u-form-item label="会员姓名:" prop="customerName" required>
                <view class="my-5rpx w-full">
                  <u-input v-model="formData.customerName" placeholder="请输入"></u-input>
                </view>
              </u-form-item>
              <u-form-item label="手机号码:" prop="customerPhone" required>
                <view class="my-5rpx w-full">
                  <u-input
                    v-model="formData.customerPhone"
                    type="number"
                    placeholder="请输入"
                    font-size="10rpx"
                  ></u-input>
                </view>
              </u-form-item>
              <u-form-item label="身份证号:" prop="cardId" required>
                <view class="my-5rpx w-full">
                  <u-input
                    type="idcard"
                    v-model="formData.cardId"
                    placeholder="请输入身份证号"
                    font-size="10rpx"
                  ></u-input>
                </view>
              </u-form-item>
            </view>
            <view class="flex justify-between">
              <u-form-item label="客户类型:" prop="customerInformationTypeId" required>
                <view class="w-full">
                  <uni-data-select
                    v-model="formData.customerInformationTypeId"
                    :localdata="customerTypeList"
                    :clear="false"
                    @change="onChangeCustomerType"
                  ></uni-data-select>
                </view>
              </u-form-item>
              <u-form-item label="家庭地址:" prop="regionCode" required>
                <view class="w-full">
                  <u-input @click="openSheet" v-model="formData.regionCodeName" placeholder="请输入家庭地址"></u-input>
                </view>
              </u-form-item>

              <u-form-item
                label="会员卡级别:"
                v-if="formData.membershipCardType == 1"
                prop="membershipLevelId"
                required
              >
                <view class="w-full">
                  <uni-data-select
                    v-model="formData.membershipLevelId"
                    :localdata="cardLevelList"
                    :clear="false"
                    @change="(item) => (formData.membershipLevelName = cardLevelList.find((v) => v.value == item).text)"
                  ></uni-data-select>
                </view>
              </u-form-item>
              <u-form-item label=" " v-else></u-form-item>
            </view>
            <view class="flex justify-between">
              <u-form-item label="物理卡号:" prop="physicalCardNumber" required>
                <view class="w-full">
                  <u-search
                    shape="square"
                    placeholder="读取卡号"
                    v-model="formData.physicalCardNumber"
                    search-icon-size="15rpx"
                    action-text="读取"
                    @custom="startReadCard"
                    :disabled="false"
                  ></u-search>
                  <!-- <u-input type="digit" v-model="formData.giveMoney" placeholder="请输入金额"></u-input> -->
                </view>
              </u-form-item>
              <u-form-item label="逻辑卡号:" prop="logicalCardNumber" required>
                <view class="w-full">
                  <u-search
                    shape="square"
                    placeholder="逻辑卡号"
                    v-model="formData.logicalCardNumber"
                    search-icon-size="15rpx"
                    action-text="刷新"
                    @custom="refreshCardNumber"
                    :disabled="false"
                  ></u-search>
                  <!-- <u-input type="digit" v-model="formData.giveMoney" placeholder="请输入金额"></u-input> -->
                </view>
              </u-form-item>
              <u-form-item label=" ">
                <view class="my-5rpx w-full">
                  <!-- 占位元素 -->
                </view>
              </u-form-item>
              <!-- <u-form-item label="是否开VA卡:" prop="openVaCard" required>
                <view class="w-full">
                  <uni-data-select
                    v-model="formData.openVaCard"
                    :localdata="[
                      { value: true, text: '是' },
                      { value: false, text: '否' },
                    ]"
                    :clear="false"
                  ></uni-data-select>
                </view>
              </u-form-item> -->
            </view>

            <view class="flex justify-between">
              <u-form-item label="办卡类型:" prop="membershipCardType" required>
                <view class="w-full">
                  <uni-data-select
                    v-model="formData.membershipCardType"
                    :localdata="[
                      { value: '1', text: '普通办卡' },
                      { value: '2', text: '套餐办卡' },
                    ]"
                    :clear="false"
                  ></uni-data-select>
                  <!-- <u-input type="digit" v-model="formData.giveMoney" placeholder="请输入金额"></u-input> -->
                </view>
              </u-form-item>

              <u-form-item label="押金:" prop="deposit" required>
                <view class="w-full">
                  <u-input v-model="formData.deposit" placeholder="请输入押金" type="digit" font-size="10rpx"></u-input>
                </view>
              </u-form-item>

              <u-form-item label="支付方式:" prop="payType" required>
                <view class="w-full">
                  <!-- <u-input
                    v-model="formData.payType"
                    placeholder="选择支付方式"
                    type="number"
                    font-size="10rpx"
                    disabled
                  ></u-input> -->
                  <uni-data-select
                    v-model="formData.payType"
                    :localdata="[
                      { value: '4', text: '现金支付' },
                      { value: '2', text: '扫码盒子' },
                    ]"
                    :clear="false"
                  ></uni-data-select>
                </view>
              </u-form-item>
            </view>

            <u-line margin="0.5em 0" v-if="formData.membershipCardType == 2" />
            <view class="flex justify-between" v-if="formData.membershipCardType == 2">
              <u-form-item label="开通套餐:" prop="membershipPackageName" required>
                <view class="w-full">
                  <u-search
                    shape="square"
                    placeholder="请选择套餐"
                    v-model="formData.membershipPackageName"
                    search-icon-size="15rpx"
                    action-text="选择"
                    @custom="openSelector"
                    :disabled="false"
                  ></u-search>
                </view>
              </u-form-item>

              <u-form-item label="套餐类型:">
                <view class="w-full">
                  <u-input disabled v-model="packageInfo.packageTypeName"></u-input>
                </view>
              </u-form-item>

              <u-form-item label="有效时间:" required prop="startDate">
                <view class="w-full">
                  <uni-datetime-picker type="daterange" v-model="packTimeRange" @change="changeDataSelect" />
                </view>
              </u-form-item>
            </view>

            <view class="flex justify-evenly" v-if="formData.membershipCardType == 2">
              <u-form-item label="用餐次数:">
                <view class="w-full">
                  <u-input type="number" disabled v-model="packageInfo.monthNum"></u-input>
                </view>
              </u-form-item>

              <u-form-item label="价格:">
                <view class="w-full">
                  <u-input type="digit" disabled v-model="packageInfo.price"></u-input>
                </view>
              </u-form-item>
            </view> </u-form
        ></u-col>
        <u-col span="3">
          <view class="ml-10rpx">
            <view>
              <text class="text-base text-gray-800">照片上传(暂不使用，请在会员编辑页采集)</text>
            </view>
            <view
              class="w-120rpx h-120rpx my-5rpx rounded-md flex justify-center items-center"
              style="border: 1px solid lightgrey"
            >
              <!-- 上传照片 -->
              <u-upload
                :file-list="fileList"
                name="propName"
                max-count="1"
                width="110rpx"
                height="110rpx"
                image-mode="aspectFill"
              >
              </u-upload>
              <!-- <u-image
                :src="formData.photo"
                mode="aspectFill"
                width="110rpx"
                height="110rpx"
                @click="openCamera"
              ></u-image> -->
            </view>
          </view>
        </u-col>
      </u-row>
      <view class="flex justify-end w-fit m-auto mt-20rpx confirm-btn centen-box">
        <view class="flex flex-auto">
          <text class="label">实收：</text>
          <text class="label price">￥{{ actualReceivedAmount }}</text>
        </view>
        <u-button type="primary" size="large" @click="saveAndPay">保存并支付</u-button>
      </view>
    </view>

    <nfc-popup ref="refNfcPopup" />

    <!-- 扫码支付弹窗 -->
    <resultPopup ref="refScanPayPopup" :show-icon="false">
      <template #default="{ result }">
        <view v-if="result.dataType == 'cash'" class="mt-20rpx flex-col items-center justify-center text-center">
          <text class="block text-base py-10rpx text-gray-400"> 找零 </text>
          <text class="block font-bold"> {{ result.giveChange || "0.00" }} 元 </text>
        </view>
        <view class="flex-col" v-else-if="result.dataType == 'scan'">
          <scanPay skipPayment :qrSize="200" @pay-finish="onScanPayFinish">
            <template #title>
              <view class="flex items-center justify-center text-center">
                <text class="block text-base"> 待收款金额: </text>
                <text class="block text-base font-bold text-red-500"> ￥{{ actualReceivedAmount }} </text>
              </view>
            </template>
          </scanPay>
        </view>
      </template>
      <template #confirm="{ config }">
        <view class="btns flex" v-if="config.confirmButton">
          <view class="btns-item" @click="refScanPayPopup.close()">
            <text class="btns-item-txt"> {{ config.confirmButton }} </text>
          </view>
        </view>
      </template>
    </resultPopup>

    <!-- 现金支付弹窗 -->
    <u-popup
      ref="refCashPayPopup"
      :show="isShowCashKeybord"
      mode="center"
      round="10rpx"
      @close="isShowCashKeybord = false"
      close-on-click-overlay
    >
      <cashPay skipPayment :modelMoney="actualReceivedAmount" @pay-finish="onCashPayFinish"> </cashPay>
    </u-popup>

    <!-- 套餐选择器 -->
    <kui-selector
      ref="kuiSelector"
      @submitItem="onSubmit"
      popupMode="right"
      :popupStyle="{
        height: '100%',
        maxWidth: '50vw',
      }"
    ></kui-selector>

    <!-- 地址选择器 -->
    <kui-tree-picker
      ref="kuiTreepPicker"
      @chargeValue="onSubmitPicker"
      :treeData="treePickeConfig.treeData"
      :lazyFun="lazyFun"
      class="kui-treep-picker"
    >
    </kui-tree-picker>

    <!-- 通知结果弹窗 -->
    <resultPopup ref="refResultPopup" :show-icon="true"> </resultPopup>
  </view>
</template>
<script setup>
import { formatMoney, getFieldValueByThisDict } from "@/utils/util";
import { reactive, ref, computed } from "vue";
import resultPopup from "@/components/common-popup/result-popup.vue";
import scanPay from "@/pages/subOrder/place-order/components/com-pay-dialog/scan-pay.vue";
import cashPay from "@/pages/subOrder/place-order/components/com-pay-dialog/cash-pay.vue";
import { bindingMembership, getCustomerType, getCustomerTypeSelect, createCardNo, appBindingMembership } from "@/api";
import { onReady } from "@dcloudio/uni-app";
import { isMobile } from "@kingon/app-tools";
import KuiSelector from "@kingon/kui-view/components/kui-selector/kui-selector.vue";
import dayjs from "dayjs";
import { useStore } from "vuex";

const store = useStore();

const fileList = ref([]);

const pageStatus = reactive({
  // 开卡状态
  openCardStatus: false,
  // 支付状态
  payStatus: false,
});

// 表单
const formData = reactive({
  customerName: "" /* 	客户姓名 */,
  customerPhone: "" /** 	手机号码 */,
  cardId: "" /** 		身份证号 */,
  customerInformationTypeId: "" /** 	客户类型 */,
  customerTypeName: "" /** 	客户类型名称 */,
  regionCode: "00" /** 		地区 (码) */,
  regionCodeName: "" /** 	地区 (名) */,
  physicalCardNumber: "" /** 		物理卡号 */,
  logicalCardNumber: "" /** 	逻辑卡号 */,
  payType: "4" /** 	支付方式（2微信3支付宝4现金） */,

  deposit: 0 /** 	押金 */,
  cardState: 5 /** 发卡状态 （1未发卡2已发卡3挂失4注销5已绑定）*/,
  /** 物理卡号和逻辑卡号是否可读，
   * 1可读，逻辑卡号和物理卡号不一样，
   * 0不可读，逻辑卡号和物理卡号一样。
   * 实际上业务没有任何区别，只是在列表中拿来看，同时可以根据这个字段搜索 */
  // readable: 1,
  opType: 1 /* 1新用户注册(开卡自动新增用户) */,
  /**
   * 数据来源（
   * 1 运营套餐充值 2 门店的套餐充值
   * 3 社区管家app帮老人办卡 4用户app开通
   * 5商家会员卡 6消费机开卡 ）
   */
  dataSource: 6,
  openVaCard: true /** 	是否开通va卡 (默认是，不给选) */,
  membershipCardType: "1" /** 	办卡类型 1普通办卡2套餐办卡 */,
  //----- 套餐 ---
  membershipPackageId: "" /** 	套餐id */,
  membershipPackageName: "" /** 	套餐名称 */,
  startDate: dayjs().format("YYYY-MM-DD HH:mm:ss") /** 	开始日期 */,
  endDate: dayjs().add(31, "day").format("YYYY-MM-DD HH:mm:ss") /** 	结束日期 */,
  //--------
  //------ 普通 ---
  openingAmount: "0.0" /** 开户金额  (普通办卡)*/,
  membershipLevelId: "" /** 	会员卡级别id */,
  membershipLevelName: "" /** 	会员卡级别名称 */,
  // giveIntegral: "0" /** 	赠送积分 */,
  // openingAmount: "0.0" /** 开户金额 */,
  // originalBalance: "0.0" /** 	原始余额 */,
  giveMoney: "0.0" /** 	赠送金额 */,
  givePoint: 0 /** 	赠送点数 */,
  //---------
  amountMoney: "0.0" /** 	实收金额 */,
});

// 表单规则
const formRules = {
  customerName: {
    type: "string",
    required: true,
    message: "请输入客户姓名",
    trigger: ["blur", "change"],
  },
  regionCode: {
    type: "string",
    required: true,
    message: "请选择家庭地址",
    trigger: ["blur", "change"],
  },
  cardId: {
    type: "string",
    required: true,
    message: "请填写正确的身份证号",
    trigger: ["blur", "change"],
    pattern: /^(\d{6})(18|19|20)?(\d{2})([01]\d)([0123]\d)(\d{3})(\d|X)?$/g,
  },
  customerInformationTypeId: {
    type: "string",
    required: true,
    message: "请选择客户类型",
    trigger: ["blur", "change"],
  },
  customerPhone: {
    type: "string",
    required: true,
    message: "请填写正确的手机号码",
    trigger: ["blur", "change"],
    validator: (rule, value) => isMobile(value),
  },
  physicalCardNumber: {
    type: "string",
    required: true,
    message: "请输读取卡号",
    trigger: ["blur", "change"],
  },
  logicalCardNumber: {
    type: "string",
    required: true,
    message: "请输获取卡号",
    trigger: ["blur", "change"],
  },
  membershipPackageName: {
    type: "string",
    required: true,
    message: "请选择套餐",
    trigger: ["blur", "change"],
  },
  startDate: {
    type: "string",
    required: true,
    message: "请选择有效期",
    trigger: ["blur", "change"],
  },
  membershipLevelId: {
    type: "string",
    required: true,
    message: "请选择会员卡级别",
    trigger: ["blur", "change"],
  },
};

onReady(() => {
  refForm.value.setRules(formRules);

  // #ifndef APP
  // if (process.env.NODE_ENV === "development") {
  //   /** ！！！！！！！！！！！！ 开发调试数据 ！！！！！！！！！！！！ */
  //   var card = "01231301";
  //   console.debug("DEV 模拟读卡", card);

  //   Object.assign(formData, {
  //     /** 如果后端开了联网核查，可能需要真实姓名以及身份证哦 */
  //     customerName: "开发老人" /* 	客户姓名 */,
  //     customerPhone: "18888880808" /** 	手机号码 */,
  //     cardId: "450122188611021512" /** 		身份证号 */,
  //     customerInformationTypeId: "" /** 	客户类型 */,
  //     customerTypeName: "无" /** 	客户类型名称 */,
  //     regionCode: "00" /** 		地区 (码) */,
  //     regionCodeName: "中国" /** 	地区 (名) */,
  //     physicalCardNumber: card /** 		物理卡号 */,
  //     logicalCardNumber: "" /** 	逻辑卡号 */,
  //     payType: "4" /** 	支付方式（2微信3支付宝4现金） */,

  //     deposit: 0 /** 	押金 */,
  //     cardState: 5 /** 发卡状态 （1未发卡2已发卡3挂失4注销5已绑定）*/,
  //     /** 物理卡号和逻辑卡号是否可读，
  //      * 1可读，逻辑卡号和物理卡号不一样，
  //      * 0不可读，逻辑卡号和物理卡号一样。
  //      * 实际上业务没有任何区别，只是在列表中拿来看，同时可以根据这个字段搜索 */
  //     // readable: 1,
  //     opType: 1 /* 1新用户注册(开卡自动新增用户) */,
  //     /**
  //      * 数据来源（
  //      * 1 运营套餐充值 2 门店的套餐充值
  //      * 3 社区管家app帮老人办卡 4用户app开通
  //      * 5商家会员卡 6消费机开卡 ）
  //      */
  //     dataSource: 6,
  //     openVaCard: false /** 	是否开通va卡 */,
  //     membershipCardType: "1" /** 	办卡类型 1普通办卡2套餐办卡 */,
  //     amountMoney: "0.0" /** 	实收金额 */,
  //     //----- 套餐 ---
  //     membershipPackageId: "" /** 	套餐id */,
  //     membershipPackageName: "" /** 	套餐名称 */,
  //     startDate: dayjs().format("YYYY-MM-DD HH:mm:ss") /** 	开始日期 */,
  //     endDate: dayjs().add(31, "day").format("YYYY-MM-DD HH:mm:ss") /** 	结束日期 */,
  //     //--------
  //     //------ 普通 ---
  //     openingAmount: "0.0" /** 开户金额  (普通办卡)*/,
  //     membershipLevelId: "" /** 	会员卡级别id */,
  //     membershipLevelName: "" /** 	会员卡级别名称 */,
  //     // giveIntegral: "0" /** 	赠送积分 */,
  //     // openingAmount: "0.0" /** 开户金额 */,
  //     // originalBalance: "0.0" /** 	原始余额 */,
  //     giveMoney: "0.0" /** 	赠送金额 */,
  //     givePoint: 0 /** 	赠送点数 */,
  //   });
  // }
  // #endif

  // 更新默认地区和地址为 商户地址
  const { regionCode, regionName } = store.getters.businessInfo;
  console.log({ regionCode, regionName });
  formData.regionCode = regionCode;
  formData.regionCodeName = regionName;
});

const refForm = ref();

// 读卡
const disabledReadBtn = ref(false);
const refNfcPopup = ref();
const startReadCard = async () => {
  if (disabledReadBtn.value) return uni.showToast({ title: "正在读卡中", icon: "none" });
  console.log("开始读卡");
  disabledReadBtn.value = true;
  try {
    // #ifdef APP
    const card = await refNfcPopup.value.reading();
    // #endif

    console.log("读卡结束", card);
    if (card) {
      formData.physicalCardNumber = card;
    }
    disabledReadBtn.value = false;
  } catch (error) {
    console.error("读卡失败", error);
    uni.showToast({ title: "读卡失败", icon: "none" });
    disabledReadBtn.value = false;
  }
};

const openCamera = () => {
  console.log("打开相机");
  uni.chooseImage({
    count: 1, //默认9
    sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ["camera"], //从相册选择
    success: function (res) {
      console.log(JSON.stringify(res.tempFilePaths));
      formData.photo = res.tempFilePaths[0];
    },
  });
};

const refResultPopup = ref();
// 刷新逻辑卡号
const refreshCardNumber = async () => {
  if (disabledReadBtn.value) return uni.showToast({ title: "刷新中", icon: "none" });
  console.log("刷新逻辑卡号");
  // 使用时间戳 + 4位随机字母/数字  作为逻辑卡号
  disabledReadBtn.value = true;
  try {
    const pam = {
      physicalCardNumber: formData.physicalCardNumber,
      autoCard: 2,
    };
    const { data, success } = await createCardNo(pam);
    if (success && data) {
      formData.logicalCardNumber = data;
      console.log("刷新逻辑卡号成功", formData);
    }
    disabledReadBtn.value = false;
  } catch (error) {
    console.error("刷新逻辑卡号失败", error);
    disabledReadBtn.value = false;
    refResultPopup.value.open({
      title: "提示",
      content: error.message || "刷新逻辑卡号失败",
      type: "fail",
    });
  }
};

// 实收金额
const actualReceivedAmount = computed(() => {
  let money = 0;

  // 根据办卡类型判断实收金额，普通： 会员开卡金额 + 押金， 套餐： 套餐金额 + 押金
  if (formData.membershipCardType == "1") {
    // 当前会员等级
    const currmeber = cardLevelList.value.find((item) => item.value == formData.membershipLevelId);
    // console.log("当前会员等级", currmeber, cardLevelList,  formData.membershipLevelId);
    money = (Number(currmeber?.openingAmount) || 0) + (Number(formData.deposit) || 0);
  } else if (formData.membershipCardType == "2") {
    // 获取当前套餐价格
    money = (Number(packageInfo.price) || 0) + (Number(formData.deposit) || 0);
  }
  formData.amountMoney = formatMoney(money);
  return formatMoney(money);
});

// 提交
const refCashPayPopup = ref();
const refScanPayPopup = ref();
const isShowCashKeybord = ref(false);

const saveAndPay = async () => {
  try {
    console.log("提交");
    // 校验表单
    await refForm.value?.validate();

    // 判断支付方式打开不同的弹窗
    if (formData.payType == "4") {
      // 成功后打开支付
      isShowCashKeybord.value = true;
    } else {
      // 成功后打开扫码支付

      const popupConfig = {
        title: "扫码支付",
        content: "",
        cancelText: "取消支付",
        autoClose: false,
        //----- 自定义数据
        dataType: "scan",
        confirmButton: "取消支付",
      };
      refScanPayPopup.value.open(popupConfig);
    }
  } catch (error) {
    console.error("表单校验未通过或其他逻辑问题： ", error);
  }
};

// 支付结束
const onCashPayFinish = async ({ type, money }) => {
  try {
    isShowCashKeybord.value = false;
    if (type === "success") {
      // 如果是现金收款，而且收款金额大于应收，则提示找零
      console.log("收款结束：", { type, money });
      const modelMoney = Number(formData.amountMoney);
      const trueMoney = Number(money);

      // 调用绑定逻辑
      await toBindingMembershipByApp();

      if (trueMoney > modelMoney) {
        // 现金支付找零
        console.log("收款金额大于应收，请找零:", trueMoney - modelMoney, "元", `${trueMoney} - ${modelMoney}`);
        refScanPayPopup.value.open({
          title: "开卡成功",
          content: "",
          closeInAfter: 600000,
          showIcon: true,
          type: "success",
          // 自定义信息
          dataType: "cash",
          state: "success",
          giveChange: `${(trueMoney - modelMoney).toFixed(2)}`,
          confirmButton: "确定",
        });
      } else {
        // 其他情况显示商户支付成
        refScanPayPopup.value.open({
          title: "开卡成功",
          closeInAfter: 100000,
          showIcon: true,
          content: "",
          type: "success",
          // 自定义信息
          state: "success",
          dataType: "none",
          confirmButton: "确定",
        });
      }
    }
  } catch (error) {
    console.error("支付结束失败", error);
  }
};

const onScanPayFinish = async ({ payBean, result }) => {
  console.log("onScanPayFinish:", { payBean, result });
  // 关闭支付弹窗
  refScanPayPopup.value.close();
  switch (payBean.status) {
    case "success":
      console.log("跳过支付组件支付逻辑，开始自定义支付逻辑");
      //  调用APP支付组件绑卡支付逻辑
      await toBindingMembershipByApp(payBean.payCode, payBean.codeType);

      break;
    case "fail":
      console.log("支付失败");
      // 其他情况显示商户支付成
      refScanPayPopup.value.open({
        title: "发起支付失败",
        showIcon: true,
        content: "",
        type: "fail",
      });
      break;
    case "cancel":
      console.log("取消支付");

      break;
    default:
  }
};

// 绑定会员
const toBindingMembership = async (money) => {
  try {
    const pam = {
      ...formData,
    };
    // 如果有实收金额，则使用实收金额 （如现金收款）
    if (money) pam.amountMoney = money;
    // 如果是普通卡，还需要删除一些字段 哈哈, 不然接口报错
    if (formData.membershipCardType == "1") {
      delete pam.startDate;
      delete pam.endDate;
      delete pam.membershipPackageId;
      delete pam.membershipPackageName;
      // delete pam.openVaCard;
    }

    const { data, success } = await bindingMembership(pam);
    if (success && data) {
      // console.log("开卡绑定会员成功", data);
      // refScanPayPopup.value.open({
      //   title: "开卡成功",
      //   closeInAfter: 100000,
      //   showIcon: true,
      //   content: "",
      //   // 自定义信息
      //   state: "success",
      //   dataType: "none",
      // });
    }
  } catch (error) {
    refScanPayPopup.value.open({
      title: "开卡失败",
      closeInAfter: 100000,
      showIcon: true,
      content: error?.data?.msg,
      type: "fail",
      // 自定义信息
      state: "fail",
      dataType: "none",
      confirmButton: "确定",
    });
    console.error("开卡绑定会员失败", error);
    // 抛出异常
    throw new Error("开卡绑定会员失败");
  }
};

// 绑定会员并支付
const toBindingMembershipByApp = async (payAuthCode, codeType) => {
  try {
    const pam = {
      ...formData,
    };
    // 如果是普通卡，还需要删除一些字段 哈哈, 不然接口报错
    if (formData.membershipCardType == "1") {
      delete pam.startDate;
      delete pam.endDate;
      delete pam.membershipPackageId;
      delete pam.membershipPackageName;
      // delete pam.openVaCard;
    }

    // 加上支付授权码 商家信息
    const { businessId } = store.getters.businessInfo;
    pam.authCode = payAuthCode;
    pam.businessId = businessId;
    pam.payType = codeType == "alipay" ? 3 : 2; // 支付方式 2微信3支付宝）
    if (!codeType) pam.payType = 4;

    // pam.deviceCode = ""

    const { data, success } = await appBindingMembership(pam);
    if (success) {
      console.log("开卡绑定会员成功", data);
      refScanPayPopup.value.open({
        title: "开卡成功",
        closeInAfter: 100000,
        showIcon: true,
        content: "",
        // 自定义信息
        state: "success",
        dataType: "none",
      });
    }
  } catch (error) {
    console.error("开卡绑定会员失败", error);
    refScanPayPopup.value.open({
      title: "开卡失败",
      closeInAfter: 100000,
      showIcon: true,
      content: error?.data?.msg,
      type: "fail",
      // 自定义信息
      state: "fail",
      dataType: "none",
      confirmButton: "确定",
    });
    // 抛出异常
    throw new Error("开卡绑定会员失败");
  }
};

// 套餐选择器
const kuiSelector = ref();
const openSelector = (e) => {
  const config = {
    action: "/kingon-service-base/businessServiceItem/packageIpage",
    pam: { dataType: 13 },
    navigationBar: ["套餐名称", "套餐类型", "价格（元）", "用餐次数", "累计方式", "适用餐别"],
    labelKey: ["itemName", "packageType", "price", "monthNum", "accumulationMethod", "mealType"],
    labelType: ["text", "text", "text", "text"],
    valueKey: "itemName",
    showSearch: true,
    showNavigationBar: true,
    searchKey: "itemName",
    format: (keyName, value, type) => {
      if (keyName === "packageType") {
        return getFieldValueByThisDict("packageType", value, dicts);
      } else if (keyName === "mealType" && value) {
        const typs = value.split(",");
        return typs.map((v) => getFieldValueByThisDict("mealType", v, dicts)).join(" | ");
      } else if (keyName === "accumulationMethod") {
        return getFieldValueByThisDict("accumulationMethod", value, dicts);
      }
      return value;
    },
  };
  kuiSelector.value.show(config);
};

const packTimeRange = ref([
  dayjs().format("YYYY-MM-DD HH:mm:ss"),
  dayjs().add(1, "months").format("YYYY-MM-DD HH:mm:ss"),
]);
const changeDataSelect = (e) => {
  console.log("changeDataSelect>>", e);
  if (e.length == 0) {
    // 清空
    formData.startDate = "";
    formData.endDate = "";
  } else {
    // [formData.startDate, formData.endDate] = e;
    formData.startDate = dayjs(e[0]).format("YYYY-MM-DD HH:mm:ss");
    formData.endDate = dayjs(e[1]).format("YYYY-MM-DD HH:mm:ss");
  }
  packTimeRange.value = e;
};

// 当前选择的套餐类型
const packageInfo = reactive({});
const onSubmit = (data) => {
  // console.log("onSubmit", data);
  if (data) {
    // packageInfo.value = data.origin.item;
    Object.assign(packageInfo, data.origin.item);
    formData.membershipPackageId = packageInfo.businessServiceItemId;
    formData.membershipPackageName = data.value;
    packageInfo.packageTypeName = getFieldValueByThisDict("packageType", packageInfo.packageType, dicts);
  }
};

// 地址选择器
const kuiTreepPicker = ref();
const treePickeConfig = reactive({
  treeData: [],
  action: "kingon-system/region/lazy-tree",
  param: {
    // parentId: 0,
    parentCode: "00",
  },
  enableLazy: false,
  props: {
    label: "title",
    children: "children",
    multiple: false,
    checkStrictly: false,
    nodes: false,
    // hasPath: false,
    postKey: "title",
  },
});
const onSubmitPicker = (val, treeData, stack) => {
  console.log("onSubmitPicker", { val, treeData, stack });
  // 获取栈数据
  formData.regionCodeName = stack.map((v) => v.title).join("");
  formData.regionCode = stack.map((v) => v.id).join("");
};

const lazyFun = async (item, parenNode, index) => {
  console.log("lazyFun", { item, parenNode, index });
  // 自定义请求，并设置数据
  const reqConf = {
    url: "/kingon-system/region/lazy-tree",
    data: { parentCode: parenNode.id },
  };
  const { data } = await uni.$kui.request(reqConf);

  const treeData = data.map((item) => {
    if (!item.children) item.children = [];
    // 设置当前层级数据是否可选，（注意：设置成false，会往下触发）
    item.canSelect = true;
    // user 这个控制是否显示右边的右箭头按钮显示，<i v-if="!item.user"
    item.user = item.hasChildren === false ? true : false;
    return item;
  });
  parenNode.children = treeData;
};

const openSheet = async () => {
  try {
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    // 请求数据
    const reqConf = {
      url: treePickeConfig.action,
      data: treePickeConfig.param || {},
      header: treePickeConfig.header,
    };

    const { data } = await uni.$kui.request(reqConf);

    // 处理请求数据
    const treeData = data.map((item) => {
      if (!item.children) item.children = [];
      // 一般树形接口
      item.canSelect = item.hasChildren == false ? false : true;
      return item;
    });
    treePickeConfig.treeData = treeData;
    kuiTreepPicker.value.open({ props: treePickeConfig.props });
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    console.error(error);
  }
};

const onChangeCustomerType = (index) => {
  const customerType = customerTypeList.value[index];
  console.log("onChangeCustomerType", customerType, index);
  formData.customerTypeName = customerType.text;
  formData.customerInformationTypeId = customerType.value;
};

// 类字典 - 客户类型
const customerTypeList = ref([]);
const customerType = async () => {
  try {
    const pam = { dataType: 1 };
    const { data, success } = await getCustomerType(pam);
    if (data) {
      customerTypeList.value = data.map((v) => {
        return { text: v.typeName, value: v.customerInformationTypeId };
      });
    }
  } catch (error) {
    console.error("获取客户类型失败: " + error.message);
  }
};

// 类字典-会员卡等级
const cardLevelList = ref([]);
const cardLevel = async () => {
  try {
    const pam = { dataType: 6 };
    const { data, success } = await getCustomerTypeSelect(pam);
    if (data) {
      cardLevelList.value = data.map((v) => {
        // 额外带有有些字段，因为计算实收需要
        return { text: v.typeName, value: v.customerInformationTypeId, openingAmount: v.openingAmount };
      });
    }
  } catch (error) {
    console.error("获取会员卡等级失败: " + error.message);
  }
};

// 获取特殊字典数据
customerType();
cardLevel();

// 其他自定义字典
const dicts = reactive({
  packageType: [
    {
      dictLabel: "日套餐",
      dictValue: "day",
    },
    {
      dictLabel: "月套餐",
      dictValue: "month",
    },
  ],
  mealType: [
    {
      dictLabel: "早餐",
      dictValue: 1,
    },
    {
      dictLabel: "午餐",
      dictValue: 2,
    },
    {
      dictLabel: "晚餐",
      dictValue: 3,
    },
    {
      dictLabel: "下午茶",
      dictValue: 4,
    },
    {
      dictLabel: "夜宵",
      dictValue: 5,
    },
  ],
  accumulationMethod: [
    {
      dictLabel: "全部清零",
      dictValue: 1,
    },
    {
      dictLabel: "全部累计",
      dictValue: 2,
    },
    {
      dictLabel: "部分累计",
      dictValue: 3,
    },
  ],
});
</script>
<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;

  ::v-deep .u-search__content__icon {
    display: none;
  }

  ::v-deep .u-upload__wrap {
    justify-content: center;
    align-items: center;
  }

  ::v-deep .u-upload__button {
    margin: 0;
  }

  .confirm-btn {
    &.centen-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 40vw;
      background-color: #f5f5f5 /* var(--kui-color-theme-light) */;
      padding: 10rpx;
      border-radius: 5rpx;

      .label {
        justify-content: center;
        display: block;
        white-space: nowrap;
        font-size: 10rpx;

        &.price {
          color: #ff0000;
          font-weight: bold;
        }
      }

      ::v-deep .u-button {
        font-size: 10rpx;
        padding: 10rpx 5rpx;
        border-radius: 4rpx;
        width: fit-content;
      }
    }

    ::v-deep .u-button {
      padding: 10rpx 30rpx;
      border-radius: 4rpx;
    }
  }
}

.btns-item {
  background-color: #efefef;
  padding: 5rpx 20rpx;
  border-radius: 5rpx;
  margin: 0rpx 15rpx;
  font-size: 12rpx;

  .btns-item-txt {
    font-size: 10rpx;
    padding: 5rpx 10rpx;
  }

  ::v-deep .u-button {
    padding: 2rpx 10rpx;
  }
}

// kui 一些组件的宽屏样式修改
::v-deep .kui-treep-picker {
  .u-popup__content {
    max-width: 54vw;
    margin: auto;
    margin-bottom: 5vh;
    border-radius: 0.3125rem;
  }
  .region-container {
    > .title {
      font-size: 10rpx;
      padding: 10rpx;
      .close,
      .close2 {
        width: 12rpx;
        height: 12rpx;
      }
    }

    .header {
      top: 32rpx;
      .title {
        font-size: 10rpx;
        padding: 10rpx;
        height: 12rpx;
        line-height: 12rpx;
      }
      .iconclass {
        font-size: 10rpx;
      }
    }

    .container-list {
      .common {
        .content {
          font-size: 10rpx;
          padding: 10rpx;
          height: 15rpx;
          .list-item {
            display: block;
            .checkbox {
              .iconfont {
                font-size: 15rpx;

                &.icon-selected {
                  font-size: 15rpx !important;
                }
              }
            }
          }
          .lable-text {
            font-size: 10rpx;
            width: fit-content;
            margin-left: 10rpx;
          }

          .right {
            .iconclass {
              font-size: 12rpx;
            }
          }
        }
      }
    }
  }
  .btn.box_sizing {
    position: sticky;
    bottom: 0;
  }
}
</style>
